package cn.thoughtworks.school.usercenter.controllers;

import cn.thoughtworks.school.usercenter.entities.User;
import cn.thoughtworks.school.usercenter.exceptions.BusinessException;
import cn.thoughtworks.school.usercenter.repositories.UserRepository;
import cn.thoughtworks.school.usercenter.services.NodeBBUserService;
import cn.thoughtworks.school.usercenter.services.ProgramService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping(value = "/api/register")
public class RegisterController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private NodeBBUserService nodeBBUserService;
    @Autowired
    private ProgramService programService;

    @RequestMapping(method = RequestMethod.POST)
    ResponseEntity register(@RequestBody User user,
                            @RequestParam(required = false, defaultValue = "") String TYPE,
                            @RequestParam(required = false) String PROGRAM) throws Exception {
        isEmailExisted(user);
        isUserNameExisted(user);
        isMobilePhoneExisted(user);
        user.setPassword(getMD5(getMD5(user.getPassword())));
        User createdUser = userRepository.save(user);
        Map<String, Long> body = new HashMap<>();
        body.put("id", createdUser.getId());

        nodeBBUserService.createNodeBBUserByUserId(createdUser.getId());
        if (needToJoinProgram(TYPE, PROGRAM)) {
            programService.joinProgram(TYPE,PROGRAM,createdUser.getId());
        }
        return new ResponseEntity(body, HttpStatus.CREATED);
    }

    private boolean needToJoinProgram(String TYPE, String PROGRAM) {
        return Objects.nonNull(TYPE) && Objects.nonNull(PROGRAM)
                && (Objects.equals("tutor", TYPE) || Objects.equals("student", TYPE))
                && Integer.parseInt(PROGRAM) > 0;
    }

    private void isEmailExisted(User user) throws BusinessException {
        if (userRepository.getUserByEmail(user.getEmail()).size() != 0) {
            throw new BusinessException("邮箱已存在！");
        }
    }

    private void isUserNameExisted(User user) throws BusinessException {
        if (userRepository.getUserByUsername(user.getUsername()).size() != 0) {
            throw new BusinessException("用户名已存在！");
        }
    }

    private void isMobilePhoneExisted(User user) throws BusinessException {
        if (userRepository.getUserByMobilePhone(user.getMobilePhone()).size() != 0) {
            throw new BusinessException("电话已存在！");
        }
    }

    private String getMD5(String str) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        String result = new BigInteger(1, md.digest()).toString(16);
        return result;
    }
}
